package com.plat.api.api.action;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.plat.api.anonation.Token;
import com.plat.api.dao.api.*;
import com.plat.api.entity.api.PlatDianzanRecordEntity;
import com.plat.api.entity.api.PlatMyWorldEntity;
import com.plat.api.entity.api.TokenEntity;
import com.plat.api.entity.api.UserEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: shish
 * Date: 2020/5/10
 * Time: 11:10
 * Description: 圈子
 */
@Service
@Token
@Slf4j
public class MyGloableAction {

    private static final Integer YES_TAP = 1;//点过赞
    private static final Integer NULL_TAP = 0;//为点过赞
    private static Integer DEFAULT_SIZE = 10;//默认大小
    private static Integer DEFAULT_PAGE = 1;//默认页数
    @Autowired
    private TokenDao tokenDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private PlatMyWorldDao platMyWorldDao;
    @Autowired
    private PlatDianzanRecordDao platDianzanRecordDao;
    @Autowired
    private PlatCommentDao platCommentDao;

    public JSONObject publish(JSONObject jsonObject) {
        JSONObject body = jsonObject.getJSONObject("body");
        String url = body.getString("url");
        String content = body.getString("content");
        Integer isSelf = body.getInteger("isSelf");
        String viewUserId = body.getString("viewUserId");
        String address = body.getString("address");
        String latitude = body.getString("latitude");
        String longitude = body.getString("longitude");
        String noViewUserId = body.getString("noViewUserId");
        String token = jsonObject.getJSONObject("head").getString("token");
        TokenEntity tokenEntity = tokenDao.getSQLManager().lambdaQuery(TokenEntity.class).andEq("token", token).single();
        UserEntity userEntity = userDao.unique(tokenEntity.getUserId());
        PlatMyWorldEntity entity = new PlatMyWorldEntity();
        entity.setUrl(url);
        entity.setContent(content);
        entity.setPublishTime(new Date());
        entity.setIsPublish(1L);
        entity.setUserId(userEntity.getId());
        entity.setIsSelf(isSelf);
        entity.setIsTop(0);
        entity.setReadNum(0);
        entity.setViewUserId(viewUserId);
        entity.setNoViewUserId(noViewUserId);
        entity.setContent(content);
        entity.setUrl(url);
        entity.setPublishTime(new Date());
        entity.setIsPublish(1L);
        entity.setUserId(0);
        entity.setIsSelf(0);
        entity.setReadNum(0);
        entity.setLikeNum(0);
        entity.setNoLikeNum(0);
        entity.setTapNum(0);
        entity.setUserId(userEntity.getId());
        entity.setPubTime("");
        entity.setIsTop(0);
        entity.setIsAdd(0);
        entity.setPublishAddress(address);
        entity.setLatitude(latitude);
        entity.setLongitude(longitude);
        //将其放入缓存中，开启线程去执行插入数据库
        platMyWorldDao.insert(entity);
        log.info("[新增圈子，圈子内容={}]",JSONObject.toJSONString(entity));
        return JSONObject.parseObject(JSONObject.toJSONString(entity));
    }

    public JSONObject getMyWorldList(JSONObject jsonObject) {
        JSONObject param = jsonObject.getJSONObject("body");
        Integer page = param.getInteger("page");
        Integer pageSize = param.getInteger("pageSize");
        if (pageSize == null) {
            pageSize = DEFAULT_SIZE;
        }
        if (page == null) {
            page = DEFAULT_PAGE;
        }
        //查缓存
        List<PlatMyWorldEntity> list2 = platMyWorldDao.createLambdaQuery().andEq("is_top", 1).orderBy("is_top =1 desc,id desc").page(page, pageSize).getList();
        List<PlatMyWorldEntity> li = new ArrayList<>();
        for (PlatMyWorldEntity entity : list2) {
            //查缓存，没有再查库
            UserEntity userEntity = userDao.single(entity.getUserId());
            entity.setUser(userEntity);
            if (StringUtils.isEmpty(entity.getPublishAddress())){
                entity.setPublishAddress("中国");
            }else {
                entity.setPublishAddress(entity.getPublishAddress());
            }
            entity.setLongTime(getDatePoor(entity.getPublishTime(), new Date()));
            entity.setPubTime(DateUtil.format(entity.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            li.add(entity);
        }
        List<PlatMyWorldEntity> list = platMyWorldDao.createLambdaQuery().andEq("is_top", 0).orderBy("id desc").page(page, pageSize).getList();
        List<PlatMyWorldEntity> li1 = new ArrayList<>();
        for (PlatMyWorldEntity entity : list) {
            //查缓存，没有再查库
            UserEntity userEntity = userDao.single(entity.getUserId());
            entity.setUser(userEntity);
            if (StringUtils.isEmpty(entity.getPublishAddress())){
                entity.setPublishAddress("中国");
            }else {
                entity.setPublishAddress(entity.getPublishAddress());
            }
            entity.setCommentNum(getCommentNum(entity.getId()));
            entity.setLongTime(getDatePoor(entity.getPublishTime(), new Date()));
            entity.setPubTime(DateUtil.format(entity.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            li1.add(entity);
        }
        li.addAll(li1);
        JSONObject json = new JSONObject();
        json.put("list", li);
        return json;
    }
     @Transactional
    public JSONObject dianZan(JSONObject jsonObject) {
        JSONObject body = jsonObject.getJSONObject("body");
        Integer id = body.getInteger("targetId");
        PlatMyWorldEntity platMyWorldEntity = platMyWorldDao.createLambdaQuery().andEq("id", id).unique();
        List<PlatDianzanRecordEntity> list = platDianzanRecordDao.createLambdaQuery()
                .andEq("target_id", platMyWorldEntity.getId()).andEq("user_id", platMyWorldEntity.getUserId()).page(1, 1).getList();
        int tapNum = platMyWorldEntity.getTapNum();
        PlatDianzanRecordEntity platDianzanRecordEntity;
        if (list.size() != 0) {
            platDianzanRecordEntity = list.get(0);
        } else {
            platDianzanRecordEntity = null;
        }
        if (platDianzanRecordEntity == null) {
            tapNum = tapNum + 1;
            platMyWorldEntity.setIsTap(YES_TAP);
            PlatDianzanRecordEntity entity = new PlatDianzanRecordEntity();
            entity.setTargetId(platMyWorldEntity.getId());
            entity.setUserId(platMyWorldEntity.getUserId());
            entity.setDianzanTime(new Date());
            platDianzanRecordDao.insert(entity);
        } else {
            platMyWorldEntity.setIsTap(NULL_TAP);
            tapNum = tapNum - 1;
            Long delId = platDianzanRecordEntity.getId();
            platDianzanRecordDao.deleteById(delId);
        }
        platMyWorldEntity.setTapNum(tapNum);
        platMyWorldDao.updateById(platMyWorldEntity);
        JSONObject json = new JSONObject();
        json.put("object", platMyWorldEntity);
        return json;
    }

    public JSONObject getMyWorld(JSONObject jsonObject) {
        JSONObject param = jsonObject.getJSONObject("body");
        Integer id = param.getInteger("id");
        PlatMyWorldEntity entity = platMyWorldDao.createLambdaQuery().andEq("id", id).single();
        PlatDianzanRecordEntity platDianzanRecordEntity = platDianzanRecordDao.createLambdaQuery()
                .andEq("target_id", entity.getId()).andEq("user_id", entity.getUserId()).single();
        if (platDianzanRecordEntity == null) {
            entity.setIsTap(NULL_TAP);
        } else {
            entity.setIsTap(YES_TAP);
        }
        entity.setReadNum(entity.getReadNum() + 1);
        platMyWorldDao.updateById(entity);
        UserEntity userEntity = userDao.single(entity.getUserId());
        entity.setUser(userEntity);
        entity.setCommentNum(getCommentNum(entity.getId()));
        entity.setLongTime(getDatePoor(entity.getPublishTime(), new Date()));
        entity.setPubTime(DateUtil.format(entity.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
        JSONObject json = new JSONObject();
        json.put("object", entity);
        return json;

    }

    public Long getCommentNum(Long id) {
        return platCommentDao.createLambdaQuery().andEq("target_id", id).count();
    }

    public String getDatePoor(Date endDate, Date nowDate) {

        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        if (day < 0) {
            day = Math.abs(day);
        }
        if (hour < 0) {
            hour = Math.abs(hour);
        }
        if (min < 0) {
            min = Math.abs(min);
        }
        return "发布 " + day + "天" + hour + "小时" + min + "分钟" + "前";
    }
}
